class Utils {
  //格式化日期
  formatDate(value, format) {
    //value: 需要进行格式化的数据, string | object
    //format: 日期的格式 yyyy符号MM符号dd hh符号mm符号ss
    let currentDate = null;

    if (Object.prototype.toString.call(value) === '[object Date]') {
      currentDate = value;
    }else {
      currentDate = new Date(value);
    }

    let year = currentDate.getFullYear();

    if (/(y+)/.test(format)) {
      //获取组匹配的内容
      let content = RegExp.$1;
      year = year.toString().slice(4 - content.length);
      format = format.replace(content, year);
    }

    let dateObject = {
      M: currentDate.getMonth() + 1,
      d: currentDate.getDate(),
      h: currentDate.getHours(),
      m: currentDate.getMinutes(),
      s: currentDate.getSeconds()
    };

    //进行替换format
    for (let key in dateObject) {
      //根据key生成动态正则表达式
      let reg = new RegExp(`(${key}+)`);

      if (reg.test(format)) {
        //获取组的匹配内容
        let c = RegExp.$1;
        let v = dateObject[key] >= 10 ? dateObject[key] : c.length === 2 ? '0' + dateObject[key] : dateObject[key];
        format = format.replace(c, v);
      }
    }

    return format;
  }

  // 随机生成颜色
  createColor() {
    let rgb = [];
    for(let i = 0; i < 3; i++) {
      let color = Math.ceil(Math.random() * 255);
      // let color = Math.ceil(Math.random() * (255 - 100) + 100);
      rgb.push(color);
    }
    return `rgb(${rgb.join(',')})`;
  }

  thousandth(number) {
    // let number = 123456789.123;
    let int = number.toString().split('.')[0];
    let float = number.toString().split('.')[1];
    let numArr = [];
    // 从后面往前面截取
    for(let i = int.length; i >= 0; i -= 3) {
      // 设置偏移量
      let left = i - 3;
      // 如果超出则设定为最小值
      if(left < 0) {
        left = 0;
      }
      let str = int.slice(left, i);
      // numArr.unshift(str);
      // 
      if(str) {
        numArr.unshift(str);
      }
    }
    // 
    let format = numArr.join(',');
    if(float) {
      format += '.' + float;
    }
    return format;
  }

}

//commonJS规范
//导入 require
//导出 module.exports, exports
module.exports = new Utils();